package lao_db

import (
	"fmt"
	config "gitee.com/laoniu11/lao-config"
	"log"
)
import "gorm.io/driver/mysql"
import "gorm.io/gorm"

var loaders = map[string]loader {
	"mysql": &MySqlLoader{},
}

type loader interface {
	load() (*gorm.DB, error)
}

type MySqlLoader struct {
	Username    string `yaml:"username"`
	Password    string `yaml:"password"`
	Host        string `yaml:"host"`
	Port        string `yaml:"port"`
	Database    string `yaml:"database"`
	MaxIdlCons  int    `yaml:"max_idl_cons"`
	MaxOpenCons int    `yaml:"max_open_cons"`
}

func (msl *MySqlLoader) load() (*gorm.DB, error) {
	msl.Username = config.GetString("mysql.username", "test")
	msl.Password = config.GetString("mysql.password", "123123")
	msl.Host = config.GetString("mysql.host", "127.0.0.1")
	msl.Port = config.GetString("mysql.port", "3306")

	database := config.GetString("mysql.database", "")
	if database == "" {
		log.Println("no database set. use test instead")
		database = "test"
	}

	msl.Database = database

	msl.MaxIdlCons = config.GetInt("mysql.max_idl_cons", 3)
	msl.MaxOpenCons = config.GetInt("mysql.max_open_cons", 10)

	return msl.open()
}

func (msl *MySqlLoader) asDsn() string {
	return fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
		msl.Username,
		msl.Password,
		msl.Host,
		msl.Port,
		msl.Database)
}

func (msl *MySqlLoader) open() (*gorm.DB, error) {
	dsn := msl.asDsn()
	log.Println("load mysql: ", dsn)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		return nil, err
	}

	sqlDb, err := db.DB()
	if err != nil {
		return nil, err
	}

	sqlDb.SetMaxIdleConns(msl.MaxIdlCons)
	sqlDb.SetMaxOpenConns(msl.MaxOpenCons)
	//sqlDb.SetConnMaxLifetime(time.Hour)
	//sqlDb.SetConnMaxIdleTime(time.Hour)

	return db, nil
}
